package com.example.factory.api.config.exception;

import com.example.factory.api.dto.Response;
import com.example.factory.core.utils.GsonUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.ss.formula.functions.T;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.AccessDeniedException;

/**
 * @author Lei Tao
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LogManager.getLogger(GlobalExceptionHandler.class);

    /**
     * 运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public Response<T> runtimeExceptionHandler(Exception e) {
        logger.error("未知异常 ===>", e);
        return Response.failed(500, "系统内部错误");
    }

    /**
     * 自定义业务异常
     */
    @ExceptionHandler(BizException.class)
    @ResponseBody
    public Response<T> bizExceptionHandler(BizException e) {
        logger.error("业务异常 ===> {}", e.errorMsg);
        logger.error(e);
        return Response.failed(e.errorCode, e.errorMsg);
    }

    /**
     * OAuth2Exception
     */
//    @ExceptionHandler(OAuth2Exception.class)
//    public void oAuth2Exception(OAuth2Exception e, HttpServletResponse response) {
//        logger.error(e);
//        try {
//            response.setStatus(401);
//            response.setContentType("application/json");
//            response.getWriter().write(GsonUtils.toJson(Response.failed(401, e.getMessage())));
//        } catch (IOException ex) {
//            ex.printStackTrace();
//        }
//    }

    /**
     * AccessDeniedException
     */
    @ExceptionHandler(AccessDeniedException.class)
    public void accessDeniedException(AccessDeniedException e, HttpServletResponse response) {
        logger.error(e);
        try {
            response.setStatus(403);
            response.setContentType("application/json");
            response.getWriter().write(GsonUtils.toJson(Response.failed(403, e.getMessage())));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
